﻿using LengthAiCalculate;

using Microsoft.VisualBasic;

using NxERP.Bll;

using System;
using System.Collections.Generic;
using System.Data;
using System.Windows.Forms;

namespace NxStoreManage
{
    public class BaseForm : Form
    {
        public static SqlHelper nxsqlHelper = new SqlHelper(SysInit.DecryptDbConn());

        public static SqlHelper sB_sqlHelper = new SqlHelper(SysInit.DecryptSbDbConn());

        public static readonly CustomerMD5 md5 = new CustomerMD5();

        public static readonly string StartupPath = Application.StartupPath;

        public static void ShowMsg(string msg, MessageBoxButtons messageBoxButtons = MessageBoxButtons.OK, MessageBoxIcon messageBoxIcon = MessageBoxIcon.Information)
        {
            MessageBox.Show(msg, "操作提示", messageBoxButtons, messageBoxIcon);
        }

        public static void OpenDir(string dir)
        {
            try { System.Diagnostics.Process.Start(dir); } finally { }
        }

        public static void ShowError(string msg = "操作错误")
        {
            MessageBox.Show(msg, "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void ShowWarning(string msg = "警告提示")
        {
            MessageBox.Show(msg, "警告提示!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static DialogResult ShowQuestion(string msg = "确定这样操作吗？")
        {
            return MessageBox.Show(msg, "确认提示?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
        }

        public static void SetDataGridDefault(DataGridView dataGridView, bool headCenter = true, bool cellCenter = false, bool enableSort = true, bool alignment = false, bool multiSelect = false, bool readOnly = true, bool rowHeadersVisible = true, bool allowUserToResizeRow = false, bool autoGenerateColumns = true, DataGridViewAutoSizeRowsMode autoSizeRowsMode = DataGridViewAutoSizeRowsMode.None, DataGridViewAutoSizeColumnsMode autoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None, DataGridViewSelectionMode selectionMode = DataGridViewSelectionMode.FullRowSelect)
        {
            dataGridView.AllowUserToAddRows = false;
            dataGridView.AllowUserToDeleteRows = false;
            dataGridView.ReadOnly = readOnly;
            dataGridView.MultiSelect = multiSelect;
            dataGridView.RowHeadersVisible = rowHeadersVisible;
            dataGridView.GridColor = System.Drawing.Color.Black;
            dataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            dataGridView.AlternatingRowsDefaultCellStyle.ForeColor = System.Drawing.Color.FromArgb(0, 0, 192);
            dataGridView.AlternatingRowsDefaultCellStyle.BackColor = System.Drawing.Color.FromArgb(224, 224, 224);
            if (headCenter)
            {
                dataGridView.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            if (cellCenter)
            {
                dataGridView.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
            }
            else
            {
                dataGridView.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            }
            if (alignment)
            {
                foreach (DataGridViewColumn item in dataGridView.Columns)
                {
                    item.CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                }
            }
            if (!enableSort)
            {
                foreach (DataGridViewColumn item in dataGridView.Columns)
                {
                    item.SortMode = DataGridViewColumnSortMode.NotSortable;
                }
            }
        }

        public static void SetShowFormDefault(Form form)
        {
            form.StartPosition = FormStartPosition.CenterScreen;
            form.FormBorderStyle = FormBorderStyle.FixedSingle;
            form.MinimizeBox = false;
            form.MaximizeBox = false;
            form.HelpButton = false;
        }

        public static void AutoSizeColumn(DataGridView dgViewFiles, int NoAutoResizeColumn = 3, bool isAutoSize = false)
        {
            if (isAutoSize)
            {
                int width = 0;
                for (int i = 0; i < dgViewFiles.Columns.Count; i++)
                {
                    dgViewFiles.AutoResizeColumn(i, DataGridViewAutoSizeColumnMode.AllCells);
                    width += dgViewFiles.Columns[i].Width;
                    if (width > dgViewFiles.Size.Width)
                    {
                        dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
                    }
                    else
                    {
                        dgViewFiles.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                    }
                }
                if (dgViewFiles.Columns.Count > NoAutoResizeColumn)
                {
                    dgViewFiles.Columns[NoAutoResizeColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                }
                dgViewFiles.ReadOnly = true;
            }
        }

        /// <summary>
        /// 获取datagridview复选框的状态
        /// </summary>
        /// <param name="row"> </param>
        /// <returns> </returns>
        public static bool GetCheckValue(DataGridViewRow row)
        {
            DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)row.Cells["cb_check"];
            if (checkCell.Value == null || !bool.Parse(checkCell.Value.ToString()))
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 获取引发右键菜单的对象实例
        /// </summary>
        /// <param name="sender"> </param>
        /// <returns> </returns>
        public static Control GetOwnerContextMenuStrip(ToolStripMenuItem sender)
        {
            return ((ContextMenuStrip)(sender.Owner)).SourceControl;//获取触发右键菜单的控件
        }

        /// <summary>
        /// datagridview复选框的状态
        /// </summary>
        /// <param name="row"> </param>
        public static void SetCheckValue(DataGridViewRow row, bool checkValue)
        {
            DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)row.Cells["cb_check"];
            checkCell.Value = checkValue;
        }

        /// <summary>
        /// 给comboBox绑定数据源
        /// </summary>
        /// <param name="comboBox">      要绑定的comboBox </param>
        /// <param name="sql">           查询的sql语句，只能绑定1列或2列；如果是2列，第1列为值，第2列为显示内容，；如果是1列，值和显示内容相同 </param>
        /// <param name="addSelectInfo"> 如果不为空，则长度必须和sql查询的列数相同 </param>
        /// <param name="comboBoxStyle"> 下拉框样式 </param>
        public static void BindComboBox(ComboBox comboBox, string sql, string[] addSelectInfo = null, ComboBoxStyle comboBoxStyle = ComboBoxStyle.DropDownList)
        {
            comboBox.DropDownStyle = comboBoxStyle;
            DataTable dt = nxsqlHelper.GetDataTableFromSql(sql);
            BindComboBox(comboBox, dt, addSelectInfo, comboBoxStyle);
        }

        /// <summary>
        /// 给comboBox绑定数据源
        /// </summary>
        /// <param name="comboBox">      要绑定的comboBox </param>
        /// <param name="dt">            绑定的数据，只能绑定1列或2列；如果是2列，第1列为值，第2列为显示内容，；如果是1列，值和显示内容相同 </param>
        /// <param name="addSelectInfo"> 如果不为空，则长度必须和dt的列数相同，且数组元素的内容必须为值、内容顺序 </param>
        /// <param name="comboBoxStyle"> 下拉框样式 </param>
        public static void BindComboBox(ComboBox comboBox, DataTable dt, string[] addSelectInfo = null, ComboBoxStyle comboBoxStyle = ComboBoxStyle.DropDownList)
        {
            comboBox.DropDownStyle = comboBoxStyle;
            comboBox.DataSource = null;
            if (dt.Rows.Count > 0)
            {
                string valueMember = null;
                string displayMember = null;
                if (dt.Columns.Count == 2)
                {
                    valueMember = dt.Columns[0].ColumnName.Trim();
                    displayMember = dt.Columns[1].ColumnName.Trim();
                }
                else if (dt.Columns.Count == 1)
                {
                    valueMember = dt.Columns[0].ColumnName.Trim();
                    displayMember = valueMember;
                }
                if (addSelectInfo != null)
                {
                    if (addSelectInfo.Length == 2)
                    {
                        DataRow dr = dt.NewRow();
                        dr[valueMember] = addSelectInfo[0];
                        dr[displayMember] = addSelectInfo[1];
                        dt.Rows.InsertAt(dr, 0);
                    }
                    else if (addSelectInfo.Length == 1)
                    {
                        DataRow dr = dt.NewRow();
                        dr[valueMember] = addSelectInfo[0];
                        dr[displayMember] = addSelectInfo[0];
                        dt.Rows.InsertAt(dr, 0);
                    }
                }
                comboBox.ValueMember = valueMember;
                comboBox.DisplayMember = displayMember;
                comboBox.DataSource = dt;
            }
        }

        public static void BindComboBox(ComboBox comboBox, List<ListItem> listItems, ComboBoxStyle comboBoxStyle = ComboBoxStyle.DropDownList)
        {
            comboBox.DataSource = null;
            comboBox.DropDownStyle = comboBoxStyle;
            comboBox.DataSource = listItems;
            comboBox.DisplayMember = nameof(ListItem.DisplayMember);
            comboBox.ValueMember = nameof(ListItem.ValueMember);
        }

        #region 添加checkbox列

        public void AddCheckBox(DataGridView dataGridView)
        {
            DataGridViewCheckBoxColumn columncb = new DataGridViewCheckBoxColumn
            {
                HeaderText = "选择"
            };
            columncb.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            columncb.Name = "cb_check";
            columncb.TrueValue = true;
            columncb.FalseValue = false;
            columncb.Width = 60;
            columncb.CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            columncb.DataPropertyName = "IsChecked";
            dataGridView.Columns.Insert(0, columncb);
            dataGridView.CellContentClick += (thisSender, thisE) =>
            {
                if (thisE.ColumnIndex == 0 && thisE.RowIndex != -1)
                {
                    DataGridView dvg = (DataGridView)thisSender;
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dvg.Rows[thisE.RowIndex].Cells["cb_check"];
                    Boolean flag = Convert.ToBoolean(checkCell.Value);
                    if (flag == true)
                    {
                        checkCell.Value = false;
                    }
                    else
                    {
                        checkCell.Value = true;
                    }
                }
            };
        }

        public void AddCheckBox(DataGridView dataGridView, string columnName, Action<List<string>> action, out List<string> checkList, Action<DataGridViewRow> rowCheckAction = null)
        {
            DataGridViewCheckBoxColumn columncb = new DataGridViewCheckBoxColumn
            {
                HeaderText = "选择"
            };
            columncb.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            columncb.Name = "cb_check";
            columncb.TrueValue = true;
            columncb.FalseValue = false;
            columncb.Width = 60;
            columncb.CellTemplate.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            columncb.DataPropertyName = "IsChecked";
            dataGridView.Columns.Insert(0, columncb);
            List<string> _checkList = new List<string>();
            dataGridView.CellContentClick += (thisSender, thisE) =>
            {
                if (thisE.ColumnIndex == 0 && thisE.RowIndex != -1)
                {
                    DataGridView dvg = (DataGridView)thisSender;
                    DataGridViewCheckBoxCell checkCell = (DataGridViewCheckBoxCell)dvg.Rows[thisE.RowIndex].Cells["cb_check"];
                    string selectStr = dvg.Rows[thisE.RowIndex].Cells[columnName].Value.ToString();
                    Boolean flag = Convert.ToBoolean(checkCell.Value);
                    if (flag == true)
                    {
                        checkCell.Value = false;
                    }
                    else
                    {
                        checkCell.Value = true;
                    }
                    if ((bool)checkCell.Value)
                    {
                        if (!_checkList.Contains(selectStr))
                        {
                            _checkList.Add(selectStr);
                        }
                        rowCheckAction?.Invoke(dvg.Rows[thisE.RowIndex]);
                    }
                    else
                    {
                        if (_checkList.Contains(selectStr))
                        {
                            _checkList.Remove(selectStr);
                        }
                        rowCheckAction?.Invoke(null);
                    }
                }
                action?.Invoke(_checkList);
            };
            checkList = _checkList;
        }

        #endregion 添加checkbox列

        public static string ShowInPutBox(string title = "输入内容", string info = "请输入内容", string defultValue = "")
        {
            return Interaction.InputBox(info, title, defultValue, -1, -1);
        }

        /// <summary>
        /// 获取引发右键菜单的对象实例
        /// </summary>
        /// <param name="sender"> </param>
        /// <returns> </returns>
        public static Control GetOwnerContextMenuStrip(object sender)
        {
            return ((ContextMenuStrip)(((ToolStripMenuItem)sender).Owner)).SourceControl;//获取触发右键菜单的控件
        }
    }

    public static class FormExt
    {
        //[DllImport("user32")]
        //public static extern int SetParentForm(int hWndChild, int hWndNewParent);

        public static void MyShowForm(this Form childForm, Form parentForm)
        {
            childForm.Show();

            //SetParentForm((int)childForm.Handle, (int)parentForm.Handle);
        }

        public static void FilterData(this DataGridView dataGridView, string filterString)
        {
            if (dataGridView.DataSource is DataTable dt)
            {
                try
                {
                    dt.DefaultView.RowFilter = filterString;
                }
                catch
                {
                    MessageBox.Show("输入的筛选条件不合法", "错误提示!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        public static void SetControlEnableState(this Form form, bool state)
        {
            foreach (Control item in form.Controls)
            {
                item.Enabled = state;
            }
        }
    }

    /// <summary>
    /// 如果窗口不需要增加到菜单，在窗体类上添加该特性
    /// </summary>
    public sealed class HideForm : Attribute
    {
    }
}